import Services from './services'
import _ from 'lodash'
import {USER_TAB_INDEX} from '../config/index'

export default {

  // 每次跳转路由时：
  // 1.首先执行服务器端函数nuxtServerInit，从服务器端session中取出user对象，写入vuex中
  // 2.然后执行鉴权中间件,从store中读取user对象
  // 注意：
  // 1.store通过vuex-persistedstate持久化，即使刷新页面，store依然存在
  // 2.store并不是只能在客户端读取，通过nuxtServerInit，服务器端也能读写store
  // 详情见https://www.jianshu.com/p/840169ba92e6
  // nuxtServerInit ({ commit }, { req }) {
  //   console.log('进入store.action.nuxtServerInit')
  //   console.log(req.session)
  //   console.log(req.session.user)

  //   if (req.session && req.session.user) {
  //     console.log(req.session.user)

  //     const { openid,name,avatar } = req.session.user
  //     const user = {
  //       openid,
  //       name,
  //       avatar
  //     }

  //     commit('SET_USER', user)
  //   }else {
  //     commit('SET_USER', null)
  //   }
  // },

  async getSeller({state}, id) {
    console.log('进入action.getSeller')
    console.log(`id:${id}`)
    const res = await Services.getSeller(id)
    state.seller = res
    return res
  },

  async getProducts({state}, id) {
    console.log('进入action.getProducts')
    const res = await Services.getProducts(id)
    state.productions = res
    return res
  },

  async getRatings({state}, id) {
    console.log('进入action.getRatings')
    const res = await Services.getRatings(id)
    state.ratings = res
    return res
  },

  async getUser({state}, id) {
    console.log('进入action.getUser')
    const res = await Services.getUser(id)
    state.user = res
    return res
  },

  async createOrder({state}, newOrder) {
    console.log('进入action.selectedProductions')
    console.log('selectedProductions:')
    console.log(newOrder)
    
    const secleteds = _.map(newOrder, 
        (item,index)=>{
          return {
            id:item.id,
            count:item.count
          }
        }
      )
    console.log('secleteds:')
    console.log(secleteds)

    const res = await Services.createOrder(newOrder)
    return res
  },

  // 设置tab页签码
  setCurrentTabIndex({commit}, current) {
    commit('SET_CURRENT_TAB_INDEX', current)
  },

  // 跳转到用户页签
  gotoUserTab({commit}) {
    commit('SET_CURRENT_TAB_INDEX',USER_TAB_INDEX)
  }

}